package own.stu.inter.loadbalance;

import org.asynchttpclient.Request;
import org.asynchttpclient.RequestBuilder;
import org.asynchttpclient.Response;
import own.stu.inter.loadbalance.httpclient.AsyncHttpHelper;
import own.stu.inter.loadbalance.server.ServerInstance;

import java.util.concurrent.CompletableFuture;

public class FakeLoadBalancerClient {

    private LoadBalancer loadBalancer;

    public FakeLoadBalancerClient(LoadBalancer loadBalancer) {
        this.loadBalancer = loadBalancer;
    }

    public CompletableFuture<Response> execute(String path) {
        return execute(null, path);
    }

    public CompletableFuture<Response> execute(ServerInstance instance, String path) {

        if (instance == null) {
            instance = loadBalancer.chooseServer(null);
        }
        if (instance == null) {
            throw new RuntimeException("no serverInstance found");
        }
        Request request = new RequestBuilder().setUrl(getSendUrl(instance, path)).build();
        return AsyncHttpHelper.getInstance().executeRequest(request);
    }

    private String getSendUrl(ServerInstance instance, String path) {
        return "http://" + instance.getId() + path;
    }
}
